package cn.cs.common;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * yuexl
 */
@Configuration
public class RabbitMQUtils {

    private Map<String, Object> args = new HashMap<>();

    @PostConstruct
    public void init(){
        // 设置该Queue的死信的信箱
        args.put("x-dead-letter-exchange", Constants.DEAD_LETTER_EXCHANGE);
        // 设置死信routingKey
        args.put("x-dead-letter-routing-key", Constants.DEAD_LETTER_ROUTINKEY);
    }
    //RabbitMQ的Queue可以配置x-dead-letter-exchange 和x-dead-letter-routing-key（可选）两个参数，如果队列内出现了dead letter，则按照这两个参数重新路由
    //声明一个死信交换机
    @Bean
    public TopicExchange deadLetterExchange() {
        return new TopicExchange(
                Constants.DEAD_LETTER_EXCHANGE,
                true,
                true);
    }

    //声明一个死信队列用来存放死信消息
    @Bean
    public Queue deadQueue() {
        return new Queue(Constants.DEAD_QUEUE,
                true,
                false,
                true,
                null);
    }

    // 将死信队列和死信的交换机绑定
    @Bean
    public Binding bindingDead() {
        return BindingBuilder.bind(deadQueue()).
                to(deadLetterExchange()).
                with(Constants.DEAD_LETTER_ROUTINKEY);
    }

    @Bean
    public Queue toQdQueue() {
        Map<String, Object> args = new HashMap<>();
        // 设置该Queue的死信的信箱
        args.put("dead-letter-exchange", Constants.DEAD_LETTER_EXCHANGE);
        // 设置死信routingKey
        args.put("dead-letter-routing-key", Constants.DEAD_LETTER_ROUTINKEY);
        return new Queue(
                Constants.RabbitQueueName.TO_QD_QUEUE,
                true,
                false,
                true, args);
    }
    @Bean
    TopicExchange topicExchange() {
        return new TopicExchange(
                Constants.RabbitQueueName.TOPIC_EXCHANGE,
                true,
                true);
    }

    @Bean
    public Binding bindingToQg() {
        return BindingBuilder.bind(toQdQueue()).to(topicExchange()).with("key.toQd");
    }

}
